﻿using System;
using System.IO;

namespace MX.Core.Caching.Redis.Serialization
{
	public class BufferHelper
	{
		static	protected byte[] ReadBytes (Stream src, int length)
		{
			var buffer = new byte[length];
			var bytesLeft = length;

			while (bytesLeft > 0)
				bytesLeft -= src.Read (buffer, length - bytesLeft, bytesLeft);

			return buffer;
		}

		static	protected void StreamCopy (Stream src, Stream dest, int count,
		                                  int bufferSize = 4096)
		{
			var bytesLeft = count;
			var buffer = new byte[bufferSize];
			while (bytesLeft > 0) {
				var chunkSize = Math.Min (bytesLeft, buffer.Length);
				var bytesRead = src.Read (buffer, 0, chunkSize);

				dest.Write (buffer, 0, bytesRead);
				bytesLeft -= bytesRead;
			}
		}

		static	public   byte[] Read (Stream src, int length)
		{
			return ReadBytes (src, length);
		}


		static	public   int GetBytesNeeded (byte[] obj)
		{
			return obj.Length;
		}

		static	public   void Write (byte[] obj, Stream dest, int bytesNeeded)
		{
			dest.Write (obj, 0, bytesNeeded);
		}
	}
}

